import React, { Component } from 'react'
import { connect } from 'dva';
import { Table, Divider, Modal, message, Icon, Popconfirm } from 'antd';
import QRCode from 'qrcode.react';
import Form from './components/SearchForm';

const ShowItem = (WrapperComponent, type, typeName) => {

  interface Props {
    dispatch?: Function,
    children?: React.ReactNode,
    loading?: boolean,
    list?: {
      data: Array<any>,
      dataCnt: number
    },
    cond?: any,
    buttons?: Array<any>,
    dict?: object,
  }

  @connect(({ qr_code = {}, loading, menu }) => ({
    list: qr_code.list || {},
    dict: qr_code.dict,
    cond: qr_code.cond || {},
    buttons: menu.buttons,
    loading: loading.effects['qr_code/queryPage']
  }))
  class Com extends Component<Props> {

    constructor(props) {
      super(props);
      this.initCurrent = this.initCurrent.bind(this);
      this.addConfirm = this.addConfirm.bind(this);
    }
    state = {
      current: 1,
      visible: false,
      belongId: '',
      belongArr: [],
      name: '',
      isReset: false,
      selectedRowKeys: [],
      rowData: [],
      downVisible: false,
      downQrCode: '',
      belongName: ''
    };

    componentDidMount() {
      const { dispatch } = this.props;
      dispatch({ type: 'qr_code/updateCond', payload: { type, pageSize: 10 } })
    }

    queryData(offset = 1) {
      const { dispatch } = this.props;
      dispatch({
        type: 'qr_code/queryPage',
        payload: {
          pageNum: offset,
        },
      });
    }

    initCurrent() {
      this.setState({
        current: 1
      })
    }

    // shouldComponentUpdate(props, state) {
    //   return !isEqual(this.props, props) || !isEqual(this.state, state)
    // }

    handleOk = () => { // 确定新增

      const { dispatch } = this.props;
      dispatch({
        type: 'qr_code/createArr',
        payload: { list: this.state.belongArr }
      }).then(() => {
        this.setState({ visible: false })
      })
    };

    handleCancel = () => { // 取消新增
      this.setState({
        visible: false,
        isReset: true
      }, () => {
        this.setState({
          isReset: false
        })
      });
    };

    addConfirm() { // 新增二维码
      this.setState({
        visible: true
      });
    };

    downHandleOk = () => {
      this.setState({
        downVisible: false
      });
    };

    downHandleCancel = () => {
      this.setState({
        downVisible: false
      });
    };

    onSelectChange = (selectedRowKeys, rowData) => {
      this.setState({
        selectedRowKeys,
        rowData
      });
    };

    downloadFn = (qrcode) => { // 下载二维码
      this.setState({
        downQrCode: qrcode.code,
        belongName: qrcode.belongName,
        downVisible: true
      });
    };

    remove = ({ belongId, type }) => {
      const { dispatch } = this.props;
      dispatch({
        type: 'qr_code/remove',
        payload: {
          belongId,
          type
        }
      }).then(() => {
        this.queryData();
      })
    };

    onShowSizeChange = (current, pageSize) => {
      const { dispatch, cond } = this.props;
      cond.pageSize = pageSize;
      dispatch({ type: `qr_code/updateCond`, payload: cond })
    }

    convertCanvasToImage = () => {
      const downQrCode: any = document.getElementById('downQrCode');
      const url = downQrCode.toDataURL("image/png");
      const a = document.createElement('a');
      const event = new MouseEvent('click');
      a.download = this.state.belongName;
      a.href = url;
      a.dispatchEvent(event);
      this.setState({
        downVisible: false
      })
    };

    export = () => {
      if (this.state.selectedRowKeys.length === 0) {
        message.warn('请选择导出的二维码');
        return;
      }
      const { dispatch } = this.props;
      dispatch({ type: 'qr_code/exportQrcode', payload: { ids: this.state.selectedRowKeys, name: '二维码下载' } })
    }

    render() {
      const { buttons } = this.props;
      const btnList = {};
      if (Array.isArray(buttons)) {
        buttons.forEach(item => {
          btnList[item.name] = item.name
        });
      }
      const { data = [], dataCnt } = this.props.list;
      const ans = data && Array.isArray(data) ? data.map((item) => ({
        key: item.id,
        ...item
      })
      ) : [];
      const rowSelection = {
        selectedRowKeys: this.state.selectedRowKeys,
        onChange: this.onSelectChange,
      };
      const pagination = {
        total: dataCnt,
        showTotal: total => `共 ${total} 条`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onShowSizeChange,
        onChange: (current) => {
          this.setState({ current });
          this.queryData(current)
        },
      };
      const columns = [{
        title: '二维码名称',
        dataIndex: 'name',
      }, {
        title: '安装位置',
        dataIndex: 'installLocationName',
      }, {
        title: '二维码',
        dataIndex: 'code',
      }, {
        title: '生成方式',
        dataIndex: 'generationModeName',
      }, {
        title: '生成时间',
        dataIndex: 'createTime',
      }, {
        title: '操作人员',
        dataIndex: 'creatorName',
      }, {
        title: '操作', key: 'x', render: (record) => {
          return (
            <div style={{ display: 'flex' }}>
              <a
                onClick={() => { this.downloadFn(record) }}
                style={{ 'cursor': 'pointer' }}>
                下载
              </a>
              <Divider type="vertical" />
              <Popconfirm
                title="请确认是否解绑?"
                onConfirm={this.remove.bind(this, { belongId: record.belongId, type: record.type })}
                okText="确定"
                cancelText="取消"
                icon={<Icon type="exclamation-circle" />}
              >
                <a>解绑</a>
              </Popconfirm>
            </div>
          )
        }
      }];

      return (
        <div>
          <Form add={this.addConfirm} export={this.export} type={type} />
          <Modal
            title={`当前单位${typeName}`}
            width={800}
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            okText="确认"
            cancelText="取消"
          >
            <WrapperComponent
              onChange={(belongId, name) => {
                this.setState({
                  belongId,
                  name
                })
              }}
              onChanges={(arr) => {
                this.setState({
                  belongArr: arr
                })
              }}
              isReset={this.state.isReset}
            />
          </Modal>
          <Table
            columns={columns}
            pagination={pagination}
            dataSource={ans}
            bordered
            loading={this.props.loading}
            rowSelection={rowSelection}
          />
          <Modal
            title="二维码下载"
            visible={this.state.downVisible}
            onOk={this.downHandleOk}
            onCancel={this.downHandleCancel}
            footer={null}
          >
            <div style={{ 'textAlign': 'center', 'marginBottom': '30px' }}>
              <QRCode value={this.state.downQrCode} width="200px" height="200px" id="downQrCode" />
            </div>
            <div style={{ 'textAlign': 'right', 'paddingLeft': '20px' }}>
              <p style={{ 'display': 'inline-block', 'textAlign': 'center' }}>
                <Icon type="download" style={{ 'marginRight': '6px' }} />
                <span style={{ 'fontSize': '12px', 'color': '#0880DF', 'cursor': 'pointer' }} onClick={() => { this.convertCanvasToImage() }}>点击下载</span>
              </p>
            </div>
          </Modal>
        </div>
      );
    }
  }

  return Com;
}

export default ShowItem;
